﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace System.Web.Mvc
{
    public class JsonNetResult : ActionResult
    {
        public JsonNetResult()
        {
            //ContentEncoding = Encoding.UTF8;
            ContentType = "application/json";
        }

        public JsonNetResult(object data, JsonRequestBehavior jsonRequestBehavior)
            : this()
        {
            Data = data;
            JsonRequestBehavior = jsonRequestBehavior;
        }

        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        public object Data { get; set; }
        public JsonRequestBehavior JsonRequestBehavior { get; set; }


        public override void ExecuteResult(ControllerContext context)
        {
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && context.HttpContext.Request.RequestType.ToUpper().Equals("GET"))
            {
                throw new Exception("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }
            context.HttpContext.Response.ContentType = ContentType;
            context.HttpContext.Response.Write(JsonConvert.SerializeObject(this.Data));
        }
    }
}